package com.bbz.crawler.core.page.pipeline;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.bbz.crawler.core.commen.model.BbzSeq;
import com.bbz.crawler.core.commen.model.CrawlerResultDetail;
import com.bbz.crawler.core.page.model.GithubJavaModel;
import com.bbz.crawler.service.IBbzSeqService;
import com.bbz.crawler.service.ICrawlerResultDetailService;
import com.bbz.crawler.service.ICrawlerResultService;

import us.codecraft.webmagic.ResultItems;
import us.codecraft.webmagic.Task;
import us.codecraft.webmagic.pipeline.Pipeline;

@Component
public class GithubForJavaAllPipeline implements Pipeline {
	@Autowired
	private ICrawlerResultService crawlerResultService;
	@Autowired
	private ICrawlerResultDetailService crawlerResultDetailService;
	@Autowired
	private IBbzSeqService bbzSeqService;

	@Override
	public void process(ResultItems resultItems, Task task) {
		// 拼接查询条件 ，获取maxId
		EntityWrapper<BbzSeq> ew = new EntityWrapper<BbzSeq>();
		ew.setEntity(new BbzSeq());
		ew.where("table_name={0}", "crawler_result");
		BbzSeq bbzSeq = bbzSeqService.selectOne(ew);
		GithubJavaModel githubJavaModel = resultItems.get("githubJavaModel");
		// CrawlerResult入库
		githubJavaModel.getCrawlerResult().setPageUrl(resultItems.getRequest().getUrl());
		githubJavaModel.getCrawlerResult().setId(bbzSeq.getCurrentValue());
		crawlerResultService.insert(githubJavaModel.getCrawlerResult());
		// CrawlerResultDetail入库
		crawlerResultDetailService.insertBatch(githubJavaModel.getCrawlerResultDetail());
		// 更新CrawlerResultDetail 外键
		for (CrawlerResultDetail c : githubJavaModel.getCrawlerResultDetail()) {
			c.setCrawlerResultId(bbzSeq.getCurrentValue());
		}
		crawlerResultDetailService.updateAllColumnBatchById(githubJavaModel.getCrawlerResultDetail());
		// 更新bbz_seq
		bbzSeq.setCurrentValue(bbzSeq.getCurrentValue() + 1);
		bbzSeqService.update(bbzSeq, ew);

	}

}
